<?php

namespace app\admin\service\admin;

use app\admin\model\admin\Admin;
use app\admin\service\BaseService;
use support\Response;
use extend\random\Random;

class AdminService extends BaseService
{
    public function __construct(Admin $model)
    {
        $this->model = $model;
    }

    public function loadList(array $where, int $page, int $limit, $field = '*', string $order = 'id asc'): array
    {
        $model = $this->model->where($where)->field($field);
        $list = $model->page($page, $limit)->order($order)->select()->toArray();
        $count = $model->count();

        return compact('list', 'count');
    }

    public function addAddmin($data)
    {
        $data['salt'] = Random::build('alnum', 6);
        $data['password'] = md5($data['password'] . $data['salt']);
        $getId = $this->model->insertGetId($data);
        if ($getId) {
            return json(['code' => 1, 'msg' => '保存成功']);
        } else {
            return json(['code' => -1, 'msg' => '保存失败']);
        }
    }

    public function editAddmin(array $data)
    {
        $getId = $data['id'];
        $menuInfo = $this->model->find($getId);
        unset($data['id']);
        $menuInfo->save($data);

        return json(['code' => 1, 'msg' => '保存成功']);
    }

    public function delAddmin($data)
    {
        $idArr = explode(',', $data['id']);
        if (is_array($idArr)) {
            $this->model->whereIn('id', $idArr)->delete();
        } else {
            $this->model::destroy($data['id']);
        }

        return json(['code' => 1, 'msg' => '删除成功']);
    }

    public function resetPwd($data)
    {
        $data['salt'] = Random::build('alnum', 6);
        $data['password'] = md5($data['password'] . $data['salt']);

        return $this->editAddmin($data);
    }

}